package com.gpscookie.mobile;

import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Image;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;

import de.enough.polish.ui.Spacer;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TextField;
import de.enough.polish.util.Locale;

public class CreateScreen extends BasicScreen implements DownloadListener
{

	private DownloadManager dlManager = null;
	private Command cmdSave;
	private StringItem labInfo;
	private TextField txtLat;
	private TextField txtLon;	
	private TextField txtTitle;
	private TextField txtDetail;
	private TextField txtTags;
	private Display display;
	private String url = "http://gpscookie.appspot.com/mobile/minicreate";
	private String adurl = "http://www.gpscookie.cn/ad.txt";
	
	
	public CreateScreen(String title, GPSCookie globalClass) {
		super(title, globalClass);
		this.dlManager = new DownloadManager();
		
		//#style textField
		this.txtLat = new TextField(Locale.get("LAT"),"",10,TextField.DECIMAL);
		this.append(txtLat);
		//#style textField		
		this.txtLon = new TextField(Locale.get("LON"),"",10,TextField.DECIMAL);
		this.append(txtLon);		
		//#style textFieldBig	
		txtTitle = new TextField(Locale.get("TITLE"), "", 60, TextField.ANY);
		append(txtTitle);
		//#style textFieldBig		
		txtDetail = new TextField(Locale.get("DESCRIPTION"), "", 200, TextField.ANY);
		append(txtDetail);
		//#style textFieldBig		
		txtTags = new TextField(Locale.get("TAG"), "", 60, TextField.ANY);
		append(txtTags);
		
		this.cmdBack = new Command(Locale.get("BACK"), Command.SCREEN, 20);		
		this.cmdSave = new Command(Locale.get("SAVE"), Command.SCREEN, 10);
		this.addCommand(this.cmdSave);
		this.addCommand(this.cmdBack);	
		this.parentScreen = GPSCookie.mainScreen;	
		this.dlManager.download(this, this.adurl);
		
		//#style infoText
		this.labInfo = new StringItem(Locale.get("STATUS"), Locale.get("READY"));
		this.append(this.labInfo);
		
		this.txtLat.setText(GPSCookie.rmsstore.get(RMSStore.LAT, ""));
		this.txtLon.setText(GPSCookie.rmsstore.get(RMSStore.LON, ""));		
	}

	public void commandAction(Command arg0, Displayable arg1) {
		if (arg0 == cmdBack) {
			this.goBack();
		} else if (arg0 == cmdSave) {
			this.saveMission();
		}
	}
	
	private void cleanScreen() {	
		//#style infoText
		this.labInfo = new StringItem(Locale.get("STATUS"), Locale.get("WAITMSG"));
		this.append(this.labInfo);		
	}
	
	public void downloadCompleted(byte[] data) {
		this.labInfo.setText(Locale.get("READY"));
		String str = "";
		try {
			if (data==null || data.length<=0) {
				throw new Exception("Not found.");
			}
			str = GPSCookie.http2String(data);
			JSONObject json = new JSONObject(str);
			JSONArray items = json.getJSONArray("items");
			GPSCookie.setAdItems(items);
			this.appendAd();
		} catch (Exception e) {
			str = e.toString();
			this.labInfo.setText(str);
		}		
	}
	
	public void downloadError(Exception e) {
		this.labInfo.setText(e.getMessage());	
	}

	public void downloadStatus(int percent) {
		this.labInfo.setText(String.valueOf(percent)+"%");		
	}

	private void saveMission() {
		HttpConnection conn = null;
		OutputStream stream = null;
		InputStream response = null;
		try {
			conn = (HttpConnection) Connector.open(url);
			conn.setRequestMethod(HttpConnection.POST);
			byte[] payload = composePayload();
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", String.valueOf(payload.length));
			stream = conn.openOutputStream();
			stream.write(payload);
			stream.flush();
			int rc = conn.getResponseCode();
			if (rc == HttpConnection.HTTP_OK) {
				response = conn.openInputStream();
				int len = (int)conn.getLength();
				len = (len>0)?len:100;
				byte[] data = new byte[len];
				len = response.read(data);				
				this.labInfo.setText(GPSCookie.http2String(data));
			} else {
				this.labInfo.setText("POST Error.");
			}			
		} catch (Exception e) {
			this.labInfo.setText(e.toString());
		}
	}
	
	private byte[] composePayload() throws Exception
	{
		RMSStore store = GPSCookie.rmsstore;
		String rtn = "title="+GPSCookie.string2http(txtTitle.getString());
		rtn += "&description="+GPSCookie.string2http(txtDetail.getString());
		rtn += "&tags="+GPSCookie.string2http(txtTags.getString());
		String value = store.get(RMSStore.USER, "");
		if ( value == null || value.length()<=0 ) {
			throw new Exception("No user");
		} else {
			rtn +="&user="+GPSCookie.string2http(value);
		}
		value = store.get(RMSStore.PWD, "");
		if ( value == null || value.length()<=0 ) {
			throw new Exception("No password");
		} else {
			rtn +="&pwd="+GPSCookie.string2http(value);
		}
		value = store.get(RMSStore.LAT, "");
		if ( value == null || value.length()<=0 ) {
			throw new Exception("No Lat.");
		} else {
			rtn +="&lat="+value;
		}
		value = store.get(RMSStore.LON, "");
		if ( value == null || value.length()<=0 ) {
			throw new Exception("No Lon.");
		} else {
			rtn +="&lon="+value;
		}	
		System.out.println(rtn);
		return rtn.getBytes();
	}
	
}
